
import sys
import pandas as pd
import math
import base.log as llog
import matplotlib.pyplot as plot
import config

from matplotlib import font_manager

def sum_of_gram(name, data):
    localfile = config.t_localpath + "/" + name + ".jpg"
    x = []
    for v in data:
        x.insert(len(x), v[config.t_sj])
    y = []
    for v in data:
        y.insert(len(x), v[config.t_zr])

    plot.rcParams['font.family'] = config.t_fontFamily
    plot.rcParams['font.sans-serif'] = [config.t_fontFamily]
    plot.rcParams['axes.unicode_minus'] = False
    plot.xlabel(config.t_sj)
    plot.ylabel(config.t_zr)
    plot.title('资金变化')
    plot.scatter(x, y)
    for i in range(len(x)):
        s = str(y[i])
        plot.annotate(s, xy=(x[i], y[i]))
    plot.plot(x, y)
    # plot.plot(x, y, 'o')
    plot.savefig(localfile)
    # plot.show()
    plot.close()

def data_from_csv(file):
    return pd.read_csv(file, header=0,index_col=0)

def data_analyse_group(name, group):
    g_sum = []
    sub_sum = []
    index = 0
    zr = '总额'
    zrr = '转入'
    zc = '转出'
    sj = '时间'
    xm = '项目'
    label = group['总额']

    for i in label:
        vv = dict()
        vv[xm] = name
        vv[sj] = group[sj][index]

        sv = dict()
        sv[xm] = name
        sv[sj] = group[sj][index]
        if math.isnan(i):
            r = group[zrr][index] if math.isnan(group[zrr][index]) is False else 0
            c = group[zc][index] if math.isnan(group[zc][index]) is False else 0
            llog.debug("nan deal ", label[index-1], ", r = ", r, ", c = ", c, ", i = ", i)
            # 取上面一次计算之后的总额数据
            vv[zr] = g_sum[index-1][zr] + r - c
        else:
            vv[zr] = i
            if index > 0:
                sv[zr] = int(i - g_sum[index-1][zr])
                sub_sum.insert(len(sub_sum), sv)
        index = index+1
        g_sum.insert(len(g_sum), vv)

    # llog.debug(g_sum)
    # llog.debug(sub_sum)
    return g_sum, sub_sum

def data_analyse(data):
    d = data.groupby(["项目"])
    llog.debug("----------------------")
    for k, i in d:
        llog.info("k = ", k)
        g, s = data_analyse_group(k, i)
        llog.debug(g)
        llog.debug(s)
        sum_of_gram(k, s)

if __name__ == "__main__":
    data = data_from_csv(sys.argv[1])
    llog.debug(data)
    data_analyse(data)
